package com.dimaidt.girl.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author : Alex Hu
 * date : 2020/2/26 下午20:12
 * description :
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {

    /**
     * 定义切片
     */
    @Pointcut("execution(public * com.dimaidt.girl.controller.GirlController.*(..)) " +
            "||  execution(public * com.dimaidt.girl.handle.ExceptionHandle.*(..))" //同时监听ExceptionHandle异常处理类
    )
    public void log() {
    }

    @Before("log()")
    //也可直接写@Before("execution(public * com.dimaidt.girl.controller.GirlController.*(..))")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
        log.info("url={}", request.getRequestURL());
        // method
        log.info("method={}", request.getMethod());
        // ip
        log.info("ip={}", request.getRemoteAddr());
        // 类方法
        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // 参数
        log.info("args={}", joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        log.info("doAfter");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        log.info("response={}", object.toString());
    }
}
